package com.itxiao.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import java.io.ByteArrayInputStream;
import java.util.Date;
import java.util.Random;

public class AliOssUtil {
    // yourEndpoint填写Bucket所在地域对应的Endpoint
    private static final String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    // 阿里云账号AccessKey
    private static final String accessKeyId = "LTAI5t6wWFBhqjkJNh6g3ddf";
    private static final String accessKeySecret = "N5yV97UavUdn9L9jneVydJMWC7sW10";
    public static final String BUCKET="dentist-dev";
    //客户端
    private static OSS client;
    static {
        // 创建OSSClient实例。
        client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 创建存储空间名称
     * @param name 存储空间名称*/
    public static boolean create(String name){
        // 创建CreateBucketRequest对象。
        CreateBucketRequest createBucketRequest = new CreateBucketRequest(name);
        // 执行操作创建存储空间
        Bucket bucket=client.createBucket(createBucketRequest);
        return bucket!=null;
    }
    /**
     * 实现文件上传
     * @param bucket 存储空间名称
     * @param obj 存储对象名称，带文件后缀
     * @param data 文件内容
     * @return 是否成功*/
    public static boolean upload(String bucket,String obj,byte[] data){
        PutObjectRequest request = new PutObjectRequest(bucket, obj, new ByteArrayInputStream(data));
        request.setProcess("true");
        PutObjectResult result=client.putObject(request);
        return result.getResponse().getStatusCode()==200;
    }
    /**
     * 创建访问链接
     * @param bucket 存储空间名称
     * @param obj 存储对象名称，带文件后缀
     * @param etime 访问地址的失效时间
     * @return 访问地址
     * */
    public static String createUrl(String bucket, String obj, Date etime){
        return client.generatePresignedUrl(bucket,obj,etime).toString();
    }
    /**
     * 删除文件
     * @param bucket 存储空间名称
     * @param obj 存储对象名称，带文件后缀
     */
    public static void delFile(String bucket,String obj){
        client.deleteObject(bucket, obj);
    }
    /**
     * 实现文件名的重命名和限长*/
    public static String rename(String fn){
        if(fn.length()>50){
            fn=fn.substring(fn.length()-50);
        }
        return System.currentTimeMillis()+"-"+new Random().nextInt(10000)+fn;
    }
}
